JavaScript for PHP Developers by Stoyan Stefanov

JavaScript for PHP Developers by Stoyan Stefanov
Author: Stoyan Stefanov
Language: eng
Format: epub, pdf
Tags: COMPUTERS / Programming Languages / JavaScript
ISBN: 9781449320188
Publisher: O’Reilly Media
Published: 2013-04-24

var a = []; var array_like = { length: 1, 0: 1 };

If you test with:


if ('length' in array_like) {}

or


if (array_like.hasOwnProperty('0')) {}

or a similar “duck typing” pattern, you may get a false positive if it happens that the array_like object has the same properties. Duck typing means guessing the type based on some expected properties. As the saying goes, “If it walks like a duck and quacks like a duck, it must be a duck.”

Another option is to use the instanceof operator. It works in most cases, but gets confused in IE when iframes are involved: